import type { Result } from 'ahooks/lib/useRequest/src/types'
import dayjs from 'dayjs'
import { Col, DatePicker, Form, Input, Row, Select, Typography } from 'antd'
import { EnvironmentOutlined } from '@ant-design/icons'

import { selectFilterOption } from '@/utils/utils'
import { EventSelect } from '@oBiz/components/EventSelect'
import { getStatusGroupName, getStatusName } from '@oBiz/components/EventSelect/utils'
import { TCountriesRes } from '@oBiz/hooks/SWRApi/useCountries'
import { TTimeZoneRes } from '@oBiz/hooks/SWRApi/useTimeZone'
import { getLocationTypeName } from '@oBiz/TrackManage/Detail/utils'
import { IStore, useBoundStore } from '@oBiz/TrackManage/List/store'
import styles from './styles.module.less'

export const EventItem = ({
  itemKey,
  waybillNo,
  countriesRes,
  timeZoneRes,
}: {
  waybillNo: string
  itemKey: number
  countriesRes: Result<TCountriesRes, []>
  timeZoneRes: Result<TTimeZoneRes, []>
}) => {
  const eventList = useBoundStore((state: IStore) => state.eventList)

  return (
    <Row gutter={[24, 0]}>
      <Col span={12}>
        <Form.Item label="运单号" name={['content', itemKey, 'waybillNo']} initialValue={waybillNo} noStyle />
        <Form.Item
          name={['content', itemKey, 'eventTemplate']}
          label="轨迹模版"
          rules={[{ required: true, message: '请选择轨迹模版' }]}
        >
          <EventSelect outsideEventList={eventList} inputProps={{ placeholder: '请选择轨迹模版' }} />
        </Form.Item>
        {/* 当 eventTemplate 从有值变为空时，清空同级的派生字段 */}
        <Form.Item
          noStyle
          shouldUpdate={(values, prevValues) =>
            values.content?.[itemKey]?.eventTemplate !== prevValues.content?.[itemKey]?.eventTemplate
          }
        >
          {({ getFieldValue, setFieldsValue }) => {
            const tpl = getFieldValue(['content', itemKey, 'eventTemplate'])
            if (!tpl) {
              const content = getFieldValue(['content']) || []
              const next = content.map((c: any, idx: number) =>
                idx === itemKey
                  ? {
                      ...c,
                      locationType: undefined,
                      statusGroup: undefined,
                      status: undefined,
                    }
                  : c,
              )
              setFieldsValue({ content: next })
            }
            return null
          }}
        </Form.Item>
        <Form.Item
          name={['content', itemKey, 'locationType']}
          label="Location类型"
          rules={[{ required: true, message: '请选择Location类型' }]}
        >
          <Select
            placeholder="请选择Location类型"
            disabled
            options={getLocationTypeName.valueList.map(value => ({
              label: getLocationTypeName(value),
              value,
            }))}
          />
        </Form.Item>
        <Typography.Title level={5}>
          <EnvironmentOutlined style={{ marginRight: 8 }} />
          Location信息
        </Typography.Title>
        <Row gutter={[24, 0]} className={styles.location_row}>
          <Col span={12}>
            <Form.Item name={['content', itemKey, 'street1']} label="街道1">
              <Input style={{ width: '100%' }} placeholder="街道地址第一行" />
            </Form.Item>
            <Form.Item
              name={['content', itemKey, 'city']}
              label="City"
              rules={[{ required: true, message: '请输入城市' }]}
            >
              <Input style={{ width: '100%' }} placeholder="城市" />
            </Form.Item>
            <Form.Item name={['content', itemKey, 'postalCode']} label="PostalCode">
              <Input style={{ width: '100%' }} placeholder="邮政编码" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name={['content', itemKey, 'street2']} label="街道2">
              <Input style={{ width: '100%' }} placeholder="街道地址第二行" />
            </Form.Item>
            <Form.Item
              name={['content', itemKey, 'stateProvince']}
              label="StateProvince"
              rules={[{ required: true, message: '请输入州/省' }]}
            >
              <Input style={{ width: '100%' }} placeholder="州/省" />
            </Form.Item>
            <Form.Item
              name={['content', itemKey, 'countryCode']}
              label="CountryCode"
              rules={[{ required: true, message: '请选择国家代码' }]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="国家代码"
                loading={countriesRes.loading}
                options={countriesRes.data?.list.map(d => ({ label: d.code, value: d.code }))}
                filterOption={selectFilterOption}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          name={['content', itemKey, 'eventTime']}
          label="发生时间"
          rules={[{ required: true, message: '请选择发生时间' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            style={{ width: '100%' }}
            disabledDate={current => current && current > dayjs().endOf('day')}
          />
        </Form.Item>
      </Col>
      <Col span={12}>
        <Typography.Title level={5}>状态信息</Typography.Title>
        <Row gutter={[24, 0]}>
          <Col span={12}>
            <Form.Item
              name={['content', itemKey, 'statusGroup']}
              label="对应状态组"
              rules={[{ required: true, message: '请选择状态分组' }]}
            >
              <Select
                placeholder="请选择状态分组"
                disabled
                options={getStatusGroupName.valueList.map(value => ({
                  label: getStatusGroupName(value),
                  value,
                }))}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name={['content', itemKey, 'status']}
              label="对应状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select
                placeholder="请选择状态"
                disabled
                options={getStatusName.valueList.map(value => ({
                  label: getStatusName(value),
                  value,
                }))}
              />
            </Form.Item>
          </Col>
        </Row>
        <Typography.Title level={5}>EDD信息</Typography.Title>
        <Row gutter={[24, 0]}>
          <Col span={6}>
            <Form.Item name={['content', itemKey, 'currentEdd']} label="现EDD">
              <DatePicker style={{ width: '100%' }} disabled />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              noStyle
              shouldUpdate={(values, prevValues) =>
                values.content?.[itemKey]?.eventTime !== prevValues.content?.[itemKey]?.eventTime
              }
            >
              {({ getFieldValue }) => {
                const eventTime = getFieldValue(['content', itemKey, 'eventTime']) || dayjs()
                return (
                  <Form.Item
                    name={['content', itemKey, 'updateEdd']}
                    label="更新EDD"
                    rules={[{ required: true, message: '请选择更新EDD日期' }]}
                  >
                    <DatePicker
                      style={{ width: '100%' }}
                      disabledDate={current => {
                        if (!current) return true
                        const afterNow = current.isAfter(dayjs(), 'day')
                        const afterEvent = current.isAfter(eventTime, 'day')
                        const beforeLimit = current.isBefore(eventTime.add(90, 'day'), 'day')
                        // 仅允许：> 今天、> 事件时间、< 事件时间+90天；其他日期禁用
                        return !(afterNow && afterEvent && beforeLimit)
                      }}
                    />
                  </Form.Item>
                )
              }}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              name={['content', itemKey, 'updateEddZone']}
              label="时区"
              rules={[{ required: true, message: '请选择时区' }]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="时区"
                loading={timeZoneRes.loading}
                options={timeZoneRes.data?.list?.map(d => ({ label: d.utcOffset, value: d.utcOffset }))}
                filterOption={selectFilterOption}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              noStyle
              shouldUpdate={(values, prevValues) => {
                return (
                  values['content']?.[itemKey]?.currentEdd !== prevValues['content']?.[itemKey]?.currentEdd ||
                  values['content']?.[itemKey]?.updateEdd !== prevValues['content']?.[itemKey]?.updateEdd
                )
              }}
            >
              {({ getFieldValue }) => {
                const currentEdd = getFieldValue(['content', itemKey, 'currentEdd'])
                const updateEdd = getFieldValue(['content', itemKey, 'updateEdd'])
                const diffDay = currentEdd ? dayjs(updateEdd).diff(dayjs(currentEdd), 'day') : 0
                return (
                  <Form.Item label="变化">
                    <Input style={{ width: '100%' }} disabled value={diffDay === 0 ? '无变化' : diffDay} />
                  </Form.Item>
                )
              }}
            </Form.Item>
          </Col>
        </Row>
        <Form.Item name={['content', itemKey, 'nextUpdateTime']} label="下次更新时间">
          <DatePicker style={{ width: '100%' }} disabledDate={current => current && current.isBefore(dayjs(), 'day')} />
        </Form.Item>
        <Form.Item name={['content', itemKey, 'note']} label="备注">
          <Input.TextArea
            autoSize={{ minRows: 6 }}
            placeholder="请输入备注"
            style={{ width: '100%' }}
            maxLength={100}
            showCount
          />
        </Form.Item>
      </Col>
    </Row>
  )
}
